package edu.xhu.video.aliyun;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Scan {

    private static Client createClient() {
        return AliyunClient.getInstance();
    }

    /**
     * 文本审核
     */
    public static Map<String, Object> greenTextScan(String content) {

        Client client = createClient();
        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);
        //
        Map<String, Object> resultMap = new HashMap<>();
        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().isEmpty()) {
            resultMap.put("suggestion", "检测内容为空");
            System.out.println("text moderation content is empty");
            return resultMap;
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        textModerationRequest.setService("chat_detection");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            // 调用方法获取检测结果。
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);

            // 自动路由。
            if (response != null) {
                // 服务端错误，区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
                    Config config = new Config();
                    config.setAccessKeyId(AliyunClient.getAccessKeyId());
                    config.setAccessKeySecret(AliyunClient.getSecret());
                    config.setRegionId("cn-beijing");
                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
                    config.setReadTimeout(6000);
                    config.setConnectTimeout(3000);
                    Client clientRouter = new Client(config);
                    response = clientRouter.textModerationWithOptions(textModerationRequest, runtime);
                }
            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        resultMap.put("code", code);
                        if (data.getLabels().isEmpty() && data.getReason().isEmpty()) {
                            resultMap.put("suggestion", "pass");
                        } else {
                            resultMap.put("suggestion", "block");
                            resultMap.put("labels", data.getLabels());
                            resultMap.put("reason", data.getReason());
                        }
                    } else {
                        resultMap.put("code", code);
                    }
                } else {
                    resultMap.put("code", response.getStatusCode());
                    resultMap.put("msg", response.getBody().getMessage());
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException(e);
        }
        return resultMap;
    }

    /**
     * 图像审核
     */
    public static Map<String, Object> greenImageScan(String url) {
        Client client = createClient();
        Map<String, Object> resultMap = new HashMap<>();
        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();
        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", url);
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());
        if (serviceParameters.get("imageUrl") == null || serviceParameters.get("imageUrl").trim().isEmpty()) {
            resultMap.put("suggestion", "检测内容为空");
            System.out.println("image moderation imageUrl is empty");
            return resultMap;
        }
        ImageModerationRequest request = new ImageModerationRequest();
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(request, runtime);
            // 自动路由。
            if (response != null) {
                // 服务端错误，区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
                    Config config = new Config();
                    config.setAccessKeyId(AliyunClient.getAccessKeyId());
                    config.setAccessKeySecret(AliyunClient.getSecret());
                    config.setRegionId("cn-beijing");
                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
                    config.setReadTimeout(6000);
                    config.setConnectTimeout(3000);
                    Client clientRouter = new Client(config);
                    response = clientRouter.imageModerationWithOptions(request, runtime);
                }
            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    resultMap.put("requestId", body.getRequestId());
                    resultMap.put("code", body.getCode());
                    resultMap.put("msg", body.getMsg());
                    if (body.getCode() == 200) {
                        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
                        List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
                            resultMap.put("labels", result.getLabel());
                            resultMap.put("confidence", result.getConfidence());
                        }
                    }
                } else {
                    resultMap.put("code", response.getStatusCode());
                    resultMap.put("msg", response.getBody().getMsg());
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException(e);
        }
        return resultMap;
    }

    /**
     * 视频审核
     */
    public static Map<String, Object> greenVideoScan(String videoUrl) {
        Map<String, Object> resultMap = new HashMap<>();
        Client client = createClient();
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url", videoUrl);
        if (serviceParameters.get("url") == null || serviceParameters.getString("url").trim().isEmpty()) {
            resultMap.put("suggestion", "检测内容为空");
            System.out.println("video moderation url is empty");
            return resultMap;
        }
        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        // 检测类型：videoDetection
        videoModerationRequest.setService("videoDetection");
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            VideoModerationResponse response = client.videoModeration(videoModerationRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResponseBody result = response.getBody();
                resultMap.put("code", result.getCode());
                resultMap.put("requestId", result.getRequestId());
                resultMap.put("msg", result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                    resultMap.put("taskId", data.getTaskId());
                }
            } else {
                resultMap.put("code", response.getStatusCode());
                resultMap.put("msg", response.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException();
        }
        return resultMap;
    }

    public static Map<String, Object> getVideoResult(String taskId) {
        Map<String, Object> resultMap = new HashMap<>();
        Client client = createClient();

        JSONObject serviceParameters = new JSONObject();
        // 提交任务时返回的taskId。
        serviceParameters.put("taskId", taskId);
        VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
        // 检测类型：videoDetection
        videoModerationResultRequest.setService("videoDetection");
        videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
            if (response.getStatusCode() == 200 || response.getStatusCode() == 280) {
                VideoModerationResultResponseBody result = response.getBody();
                resultMap.put("code", result.getCode());
                resultMap.put("requestId", result.getRequestId());
                resultMap.put("msg", result.getMessage());
                if (200 == result.getCode()) {
                    VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                    resultMap.put("dataId", data.getDataId());
                    resultMap.put("audioResult", JSON.toJSONString(data.getAudioResult()));
                    resultMap.put("frameResult", JSON.toJSONString(data.getFrameResult()));
                    resultMap.put("frameNum", data.getFrameResult().getFrameNum());
                }
            } else {
                resultMap.put("code", response.getStatusCode());
                resultMap.put("msg", response.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException();
        }
        return resultMap;
    }

}